<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    Nodejs快速上手.md |  Small Bridge
  </title>
  <meta name="generator" content="hexo-theme-yilia-plus">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/css/main.css">

  
  <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
  
  

  

<link rel="alternate" href="/atom.xml" title="Small Bridge" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    <main class="content">
      <section class="outer">
  <article id="post-Nodejs快速上手-md" class="article article-type-post" itemscope
  itemprop="blogPost" data-scroll-reveal>

  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Nodejs快速上手.md
</h1>
  

    </header>
    

    
    <div class="article-meta">
      <a href="/2020/09/07/Nodejs%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B-md/" class="article-date">
  <time datetime="2020-09-07T13:19:47.000Z" itemprop="datePublished">2020-09-07</time>
</a>
      
  <div class="article-category">
    <a class="article-category-link" href="/categories/JavaScript/">JavaScript</a>
  </div>

      
      
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">2.2k字</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">9分钟</span>
        </span>
    </span>
</div>

      
    </div>
    

    
    
    <div class="tocbot"></div>





    

    
    <div class="article-entry" itemprop="articleBody">
      


      

      
      <p>@<a href="Node.js">TOC</a></p>
<a id="more"></a>
<p>nodej是一个JavaScript运行环境(runtime)。它让JavaScript可以开发后端程序，它几乎能实现其它后端语言能实现的所有功能，nodejs最擅长处理高并发<br><img src="https://img-blog.csdnimg.cn/20200729093112238.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0NjI1MTQy,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>我没有对各个模块进行相应的描述，而是直接使用代码，让你快速上手</p>
<h1 id="HTTP、URL模块"><a href="#HTTP、URL模块" class="headerlink" title="HTTP、URL模块"></a>HTTP、URL模块</h1><ol>
<li><p>创建一个web服务器<br>http模块</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建一个web服务器</span></span><br><span class="line"><span class="comment">//引入模块</span></span><br><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>)</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* req  获取客户端传过来的信息</span></span><br><span class="line"><span class="comment">* res  给浏览返回信息</span></span><br><span class="line"><span class="comment">* */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//调用函数</span></span><br><span class="line">http.createServer(<span class="function">(<span class="params">req,res</span>) =&gt;</span> &#123;</span><br><span class="line"><span class="comment">//设置响应头部</span></span><br><span class="line">res.writeHead(<span class="number">200</span>,&#123;<span class="string">"Content-Type"</span>:<span class="string">"text/plain"</span>&#125;)</span><br><span class="line"><span class="comment">//返回数据</span></span><br><span class="line">res.end(<span class="string">"Hello World"</span>)</span><br><span class="line">&#125;).listen(<span class="number">8081</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">"Server running at http://127.0.0.1:8081/"</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>解析url地址<br>url模块</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//引入</span></span><br><span class="line"><span class="keyword">const</span> url = <span class="built_in">require</span>(<span class="string">'url'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//模拟请求</span></span><br><span class="line"><span class="keyword">var</span> api = <span class="string">'http://www.cxq.com?name=cxq&amp;age=21'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// console.log(url.parse(api))   解析地址</span></span><br><span class="line"><span class="comment">// console.log(url.parse(api,true))  解析地址，并且query变成对象</span></span><br><span class="line"><span class="keyword">var</span> getValue = url.parse(api,<span class="literal">true</span>).query</span><br><span class="line"></span><br><span class="line"><span class="comment">//获取请求的get传值</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">`姓名: <span class="subst">$&#123;getValue.name&#125;</span>----年龄: <span class="subst">$&#123;getValue.age&#125;</span>`</span>)</span><br></pre></td></tr></table></figure>
<p>http和url二者结合使用<br>获取网页的get传值</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>)   <span class="comment">//引入模块</span></span><br><span class="line"><span class="keyword">const</span> url = <span class="built_in">require</span>(<span class="string">'url'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//创建服务器</span></span><br><span class="line">http.createServer( <span class="function">(<span class="params">req,res</span>) =&gt;</span>&#123;</span><br><span class="line">  <span class="comment">//设置响应头部</span></span><br><span class="line">  res.writeHead(<span class="number">200</span>,&#123;<span class="string">"Content-Type"</span>:<span class="string">"text/html;charset='utf-8'"</span>&#125;) <span class="comment">//解决乱码</span></span><br><span class="line">  res.write(<span class="string">"&lt;head&gt;&lt;meta charset='UTF-8'/&gt;&lt;/head&gt;"</span>) <span class="comment">//解决乱码</span></span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.log(req.url)  <span class="comment">//获取浏览器访问的地址</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (req.url != <span class="string">'/favicon.ico'</span>)&#123;</span><br><span class="line">    <span class="keyword">var</span> getValue = url.parse(req.url,<span class="literal">true</span>).query</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`姓名: <span class="subst">$&#123;getValue.name&#125;</span>----年龄:<span class="subst">$&#123;getValue.age&#125;</span>`</span>)</span><br><span class="line">  &#125; </span><br><span class="line">  </span><br><span class="line"></span><br><span class="line">  res.end(<span class="string">"你好，Node.js"</span>) <span class="comment">//结束响应</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;).listen(<span class="number">3001</span>)  <span class="comment">//监听端口</span></span><br></pre></td></tr></table></figure>
<p>控制台会打印出你在浏览器中输入的?get传值</p>
<h1 id="COMMONjs和Nodejs模块，自定义模块"><a href="#COMMONjs和Nodejs模块，自定义模块" class="headerlink" title="COMMONjs和Nodejs模块，自定义模块"></a>COMMONjs和Nodejs模块，自定义模块</h1><p>COMMONjs就是一个模块化的标准，而这个标准的实现就是nodejs</p>
</li>
<li><p>模块的分类<br>核心模块(内置模块): nodejs提供的模块，如http，url，path<br>文件模块(自定义模块):用户自己编写的</p>
</li>
<li><p>commonjs模块化标准<br>我们可以把公共的功能抽离成一个单独的js文件作为一个模块，默认这个模块中的属性和方法是私有的，但可以通过exports和module.exports向外暴露<br>有需要的时候模块之间可以通过require引入<br>单独的一个函数一般使用exports暴露，module.exports一般用来暴露对象</p>
</li>
<li><p>在引入模块时，默认会寻找node_modules文件下的模块名下的index.js，这都是commonjs规定好的，可以通过配置文件package.json修改，package.json可以通过npm init生成<br><img src="https://img-blog.csdnimg.cn/20200729095506794.png" alt="在这里插入图片描述"></p>
</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> axios = <span class="built_in">require</span>(<span class="string">'axios'</span>)</span><br><span class="line"><span class="keyword">const</span> db  = <span class="built_in">require</span>(<span class="string">'db'</span>)</span><br><span class="line">axios.get()</span><br><span class="line">axios.post()</span><br><span class="line">db.add()</span><br></pre></td></tr></table></figure>
<h1 id="包，npm，cnpm，第三方模块，package-json"><a href="#包，npm，cnpm，第三方模块，package-json" class="headerlink" title="包，npm，cnpm，第三方模块，package.json"></a>包，npm，cnpm，第三方模块，package.json</h1><ol>
<li>包含有模块的就是包</li>
<li>npm 是包管理工具，可以通过它往一个项目中添加或者删除包</li>
<li>别人写好的模块放到网上供我们随意使用的就是第三方模块，可以在npmjs官网寻找</li>
<li>cnpm是淘宝镜像，在国内，下包速度更快</li>
<li>package.json是项目的配置描述文件，很重要<br><img src="https://img-blog.csdnimg.cn/20200729100041415.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0NjI1MTQy,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></li>
</ol>
<p>里面包含了对项目的一些描述，比如dependencies就是项目运行所必需的依赖，后面的数字就是依赖的版本号，^表示第一位版本号不变，后两位取最新，~表示前两位版本不变，后一位取最新，*表示全部取最新</p>
<p>我们可以通过npm(cnpm)下载和使用包，比如使用MD5实现加密的功能<br>项目中运行<br>npm install md5 –save 下载包<br>根据文档使用<br><a href="https://www.npmjs.com/" target="_blank" rel="noopener">npmjs官网</a></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> md5 = <span class="built_in">require</span>(<span class="string">'md5'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//实现md5加密的功能</span></span><br><span class="line"><span class="built_in">console</span>.log(md5(<span class="number">123456</span>))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//格式日期</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">new</span> <span class="built_in">Date</span>())</span><br></pre></td></tr></table></figure>
<h1 id="fs模块"><a href="#fs模块" class="headerlink" title="fs模块"></a>fs模块</h1><p>fs模块实现了对文件的一系列操作，是nodejs中非常重要的部分</p>
<ol>
<li><p>常用的方法</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* 1. fs.stat   检查是文件还是目录</span></span><br><span class="line"><span class="comment">* 2. fs.mkdir  创建目录</span></span><br><span class="line"><span class="comment">* 3. fs.writeFile 创建写入文件</span></span><br><span class="line"><span class="comment">* 4. fs.appendFile 追加文件</span></span><br><span class="line"><span class="comment">* 5. fs.readFile 读取文件</span></span><br><span class="line"><span class="comment">* 6. fs.readdir 读取目录</span></span><br><span class="line"><span class="comment">* 7. fs.reanme  重命名</span></span><br><span class="line"><span class="comment">* 8. fs.rmdir   删除目录</span></span><br><span class="line"><span class="comment">* 9. fs.unlink  删除文件</span></span><br><span class="line"><span class="comment">* */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// * 1. fs.stat   检查是文件还是目录</span></span><br><span class="line"><span class="comment">// fs.stat('./html',function (err,data) &#123;</span></span><br><span class="line"><span class="comment">//   if(err)&#123;</span></span><br><span class="line"><span class="comment">//     console.log(err)</span></span><br><span class="line"><span class="comment">//     return</span></span><br><span class="line"><span class="comment">//   &#125;</span></span><br><span class="line"><span class="comment">//   console.log(`是文件:$&#123;data.isFile()&#125;`)</span></span><br><span class="line"><span class="comment">//   console.log(`是目录:$&#123;data.isDirectory()&#125;`)</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// * 2. fs.mkdir  创建目录 再次创建会报错已存在</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* path    将创建的目录路径</span></span><br><span class="line"><span class="comment">* mode    目录权限(读写权限)，默认777</span></span><br><span class="line"><span class="comment">* callback  回调，传递异常参数err</span></span><br><span class="line"><span class="comment">* */</span></span><br><span class="line"><span class="comment">// fs.mkdir('./css',err =&gt; &#123;</span></span><br><span class="line"><span class="comment">//   if (err)&#123;</span></span><br><span class="line"><span class="comment">//     console.log(err)</span></span><br><span class="line"><span class="comment">//     return</span></span><br><span class="line"><span class="comment">//   &#125;</span></span><br><span class="line"><span class="comment">//   console.log('创建成功')</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// * 3. fs.writeFile 创建并写入文件,再次写入的时候会替换</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* filename     文件名称</span></span><br><span class="line"><span class="comment">* data         数据</span></span><br><span class="line"><span class="comment">* options      option数组对象 ，包含：</span></span><br><span class="line"><span class="comment">*  . enconding  文件编码</span></span><br><span class="line"><span class="comment">*  . mode       文件读写权限，默认值438</span></span><br><span class="line"><span class="comment">*  . flag       默认值 w</span></span><br><span class="line"><span class="comment">* callback      回调函数</span></span><br><span class="line"><span class="comment">* */</span></span><br><span class="line"><span class="comment">// fs.writeFile('./html/index.html','你好，nodejs,好不好!',err =&gt;&#123;</span></span><br><span class="line"><span class="comment">//   if (err)&#123;</span></span><br><span class="line"><span class="comment">//     console.log(err)</span></span><br><span class="line"><span class="comment">//     return</span></span><br><span class="line"><span class="comment">//   &#125; </span></span><br><span class="line"><span class="comment">//   console.log('创建写入文件成功')</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// * 4. fs.appendFile 追加文件 不存在创建并写入，存在则追加</span></span><br><span class="line"><span class="comment">// fs.appendFile('./css/base.css','h2&#123;color:red&#125;',err =&gt;&#123;</span></span><br><span class="line"><span class="comment">//   if (err)&#123;</span></span><br><span class="line"><span class="comment">//     console.log(err)</span></span><br><span class="line"><span class="comment">//     return</span></span><br><span class="line"><span class="comment">//   &#125; </span></span><br><span class="line"><span class="comment">//   console.log('appendFile 成功!')</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// * 5. fs.readFile 读取文件</span></span><br><span class="line"><span class="comment">// fs.readFile('./html/index.html',(err,data) =&gt; &#123;</span></span><br><span class="line"><span class="comment">//   if (err)&#123;</span></span><br><span class="line"><span class="comment">//     console.log(err)</span></span><br><span class="line"><span class="comment">//     return</span></span><br><span class="line"><span class="comment">//   &#125;</span></span><br><span class="line"><span class="comment">//   console.log(data)  //默认是Buffer类型的数据</span></span><br><span class="line"><span class="comment">//   console.log(data.toString())</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// * 6. fs.readdir 读取目录 返回当前目录下所有的文件以及文件夹的数组</span></span><br><span class="line"><span class="comment">// fs.readdir('./html',(err,data) =&gt; &#123;</span></span><br><span class="line"><span class="comment">//   if (err)&#123;</span></span><br><span class="line"><span class="comment">//     console.log(err)</span></span><br><span class="line"><span class="comment">//     return</span></span><br><span class="line"><span class="comment">//   &#125;</span></span><br><span class="line"><span class="comment">//   console.log(data)</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// * 7. fs.reanme  重命名  修改名称 或者 达到移动文件的效果</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// fs.rename('./css/aaa.css','./css/index.css',err =&gt; &#123;</span></span><br><span class="line"><span class="comment">//   if (err)&#123;</span></span><br><span class="line"><span class="comment">//     console.log(err)</span></span><br><span class="line"><span class="comment">//     return</span></span><br><span class="line"><span class="comment">//   &#125; </span></span><br><span class="line"><span class="comment">//   console.log('重命名成功!')</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// fs.rename('./css/index.css','./html/index.css',err =&gt; &#123;</span></span><br><span class="line"><span class="comment">//   if (err)&#123;</span></span><br><span class="line"><span class="comment">//     console.log(err)</span></span><br><span class="line"><span class="comment">//     return</span></span><br><span class="line"><span class="comment">//   &#125;</span></span><br><span class="line"><span class="comment">//   console.log('移动成功')</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// * 8. fs.rmdir   删除目录</span></span><br><span class="line"><span class="comment">// fs.rmdir('./aaa',err =&gt;&#123;</span></span><br><span class="line"><span class="comment">//   if (err)&#123;</span></span><br><span class="line"><span class="comment">//     console.log(err)</span></span><br><span class="line"><span class="comment">//     return</span></span><br><span class="line"><span class="comment">//   &#125;</span></span><br><span class="line"><span class="comment">//   console.log('删除目录成功')</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//  * 9. fs.unlink  删除文件</span></span><br><span class="line"><span class="comment">// fs.unlink('./aaa/index.html',err=&gt;&#123;</span></span><br><span class="line"><span class="comment">//   if (err)&#123;</span></span><br><span class="line"><span class="comment">//     console.log(err)</span></span><br><span class="line"><span class="comment">//     return</span></span><br><span class="line"><span class="comment">//   &#125;</span></span><br><span class="line"><span class="comment">//   console.log('删除文件成功')</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br></pre></td></tr></table></figure></li>
<li><p>案例</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//判断服务器上面有没有upload目录，如果没有创建这个目录，如果有的话不做操作 (图片操作</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>)</span><br><span class="line"><span class="keyword">var</span> path = <span class="string">'./upload'</span></span><br><span class="line"></span><br><span class="line">fs.stat(path,(err,data) =&gt; &#123;</span><br><span class="line">  <span class="keyword">if</span> (err)&#123;</span><br><span class="line">    mkdir(path)</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (data.isDirectory())&#123;</span><br><span class="line">     <span class="built_in">console</span>.log(<span class="string">'upload目录已经存在'</span>)</span><br><span class="line">  &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">    <span class="comment">//删除原来的文件，创建目录</span></span><br><span class="line">    fs.unlink(path,err =&gt; &#123;</span><br><span class="line">      <span class="keyword">if</span> (!err)&#123;</span><br><span class="line">        mkdir(path)</span><br><span class="line">      &#125; <span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'创建目录失败!'</span>)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">mkdir</span>(<span class="params">path</span>) </span>&#123;</span><br><span class="line">  fs.mkdir(path,err =&gt;&#123;</span><br><span class="line">    <span class="keyword">if</span> (err)&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(err)</span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">    &#125; </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'创建成功'</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//找出wwwroot中所有的文件以及文件夹，将其中的目录放在一个数组中</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//使用递归和自执行完成</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//nodejs中的很多方法 都是异步的</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>)</span><br><span class="line"><span class="keyword">var</span> path = <span class="string">'./wwwroot'</span></span><br><span class="line"><span class="keyword">var</span> dirArr = []</span><br><span class="line"></span><br><span class="line">fs.readdir(path,(err,data) =&gt; &#123;</span><br><span class="line">  <span class="keyword">if</span> (err)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(err)</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  &#125;</span><br><span class="line">  (<span class="function"><span class="keyword">function</span> <span class="title">getDir</span>(<span class="params">i</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(i == data.length)&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(dirArr)</span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    fs.stat(path + <span class="string">'/'</span> + data[i],(error,stats) =&gt;&#123;</span><br><span class="line">      <span class="keyword">if</span> (stats.isDirectory())&#123;</span><br><span class="line">        dirArr.push(data[i])</span><br><span class="line">      &#125;</span><br><span class="line">      getDir(i+<span class="number">1</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;)(<span class="number">0</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>我们还可以使用async和await完成这个任务<br>async是让方法成为异步<br>await是等待异步完成，它只能在异步方法中使用<br>Promise是异步编程的一种解决方案，可用于返回异步数据</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>)</span><br><span class="line"><span class="keyword">var</span> path = <span class="string">'./wwwroot'</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">isDir</span>(<span class="params">path</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>)=&gt;</span>&#123;</span><br><span class="line">    fs.stat(path,(err,data) =&gt;&#123;</span><br><span class="line">      <span class="keyword">if</span> (err)&#123;</span><br><span class="line">        reject(err)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">      &#125; </span><br><span class="line">      <span class="keyword">if</span> (data.isDirectory)&#123;</span><br><span class="line">        resolve(<span class="literal">true</span>)</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        resolve(<span class="literal">false</span>)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> path = <span class="string">'./wwwroot'</span></span><br><span class="line">  <span class="keyword">var</span> dirArr = []</span><br><span class="line">  fs.readdir(path,<span class="keyword">async</span> (err,dta) =&gt;&#123;</span><br><span class="line">    <span class="keyword">if</span> (err)&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(err)</span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; dta.length; i++) &#123;</span><br><span class="line">      <span class="keyword">if</span>(<span class="keyword">await</span> isDir(path + <span class="string">'/'</span> + dta[i])) &#123;</span><br><span class="line">        dirArr.push(dta[i])</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">console</span>.log(dirArr)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br><span class="line">main()</span><br></pre></td></tr></table></figure>
<p>当然，我们完全可以使用同步的方法去写，这样免去了很多麻烦，但是异步的更不容易想出来，因为它执行的顺序在同步之后，希望大家理解这种写法</p>
</li>
<li><p>以流的方式读取和写入文件(适用于大文件的读写)</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> readStream = fs.createReadStream(<span class="string">'./data/input.txt'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> str = <span class="string">""</span></span><br><span class="line"><span class="keyword">var</span> count = <span class="number">0</span></span><br><span class="line">readStream.on(<span class="string">'data'</span>,data=&gt;&#123;</span><br><span class="line">  str += data</span><br><span class="line">  count++</span><br><span class="line">&#125;)</span><br><span class="line">readStream.on(<span class="string">'end'</span>,()=&gt;&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(str)</span><br><span class="line">  <span class="built_in">console</span>.log(count)</span><br><span class="line">&#125;)</span><br><span class="line">readStream.on(<span class="string">'error'</span>,err=&gt;&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(err)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>读取流读取文件时是一点一点读取的，所以需要监听事件才能获取读取的数据</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> str = <span class="string">'我是数据\n'</span>.repeat(<span class="number">500</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> writeStream = fs.createWriteStream(<span class="string">'./data/output.txt'</span>)</span><br><span class="line"></span><br><span class="line">writeStream.write(str)</span><br><span class="line"></span><br><span class="line"><span class="comment">//标记文件末尾 不写这个则下面的监听finish事件没有作用</span></span><br><span class="line">writeStream.end()</span><br><span class="line"></span><br><span class="line">writeStream.on(<span class="string">'finish'</span>,()=&gt;&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'写入完成'</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>管道流(将读取的直接写入)</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//管道流</span></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> readStream = fs.createReadStream(<span class="string">'./data/input.txt'</span>)</span><br><span class="line"><span class="keyword">var</span> writeStream = fs.createWriteStream(<span class="string">'./test.txt'</span>)</span><br><span class="line"></span><br><span class="line">readStream.pipe(writeStream)</span><br></pre></td></tr></table></figure>
<p>好了，我的分享就到这里了，谢谢大家</p>
</li>
</ol>

      
      <!-- reward -->
      
      <div id="reward-btn">
        打赏
      </div>
      
    </div>
    
    
      <!-- copyright -->
      
        <div class="declare">
          <ul class="post-copyright">
            <li>
              <i class="ri-copyright-line"></i>
              <strong>版权声明： </strong s>
              本博客所有文章除特别声明外，均采用 <a href="https://www.apache.org/licenses/LICENSE-2.0.html" rel="external nofollow"
                target="_blank">Apache License 2.0</a> 许可协议。转载请注明出处！
            </li>
          </ul>
        </div>
        
    <footer class="article-footer">
      
          
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://lockme.gitee.io/2020/09/07/Nodejs%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B-md/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JavaScript/" rel="tag">JavaScript</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Node-js/" rel="tag">Node.js</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E6%8A%80%E6%9C%AF/" rel="tag">技术</a></li></ul>


    </footer>

  </div>

  
  
  <nav class="article-nav">
    
      <a href="/2020/09/07/%E4%BD%BF%E7%94%A8%E5%8E%9F%E7%94%9Fnodejs%E6%90%AD%E5%BB%BA%E7%AE%80%E5%8D%95%E9%9D%99%E6%80%81Web%E6%9C%8D%E5%8A%A1%E5%99%A8-md/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            使用原生nodejs搭建简单静态Web服务器.md
          
        </div>
      </a>
    
    
      <a href="/2020/09/07/Node-js%E7%AE%80%E5%8D%95%E5%85%A5%E9%97%A8%E4%BB%8B%E7%BB%8D-md/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">Node.js简单入门介绍.md</div>
      </a>
    
  </nav>


  

  
  
<!-- valine评论 -->
<div id="vcomments-box">
    <div id="vcomments">
    </div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='https://cdn.jsdelivr.net/npm/valine@1.3.10/dist/Valine.min.js'></script>
<script>
    new Valine({
        el: '#vcomments',
        app_id: 'pmaQYnbUE9O0H1hiYKLiec4R-gzGzoHsz',
        app_key: 'LMujtI79W4vgEQ3Az5IMo50y',
        path: window.location.pathname,
        notify: 'false',
        verify: 'false',
        avatar: 'mp',
        placeholder: '给我的文章加点评论吧~',
        recordIP: true
    });
    const infoEle = document.querySelector('#vcomments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
        infoEle.childNodes.forEach(function (item) {
            item.parentNode.removeChild(item);
        });
    }
</script>
<style>
    #vcomments-box {
        padding: 5px 30px;
    }

    @media screen and (max-width: 800px) {
        #vcomments-box {
            padding: 5px 0px;
        }
    }

    #vcomments-box #vcomments {
        background-color: #fff;
    }

    .v .vlist .vcard .vh {
        padding-right: 20px;
    }

    .v .vlist .vcard {
        padding-left: 10px;
    }
</style>

  

  
  
  

</article>
</section>
      <footer class="footer">
  <div class="outer">
    <ul class="list-inline">
      <li>
        &copy;
        2020
        月下ctrlc
      </li>
      <li>
        
        Powered by
        
        
        <a href="https://hexo.io" target="_blank">Hexo</a> Theme <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul class="list-inline">
      <li>
        
        
        <span>
  <i>PV:<span id="busuanzi_value_page_pv"></span></i>
  <i>UV:<span id="busuanzi_value_site_uv"></span></i>
</span>
        
      </li>
      
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="to_top">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>
      </div>
    </main>
    <aside class="sidebar">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/avatar.jpg" alt="Small Bridge"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Vue/">Vue</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="http://shenyu-vip.lofter.com" target="_blank" rel="noopener">主题作者相册</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2020/03/18/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>拿钱砸死我吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.png">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.png">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/share.js"></script>


<script src="/js/lazyload.min.js"></script>


<script>
  try {
    var typed = new Typed("#subtitle", {
      strings: ['面朝大海，春暖花开', '愿你一生努力，一生被爱', '想要的都拥有，得不到的都释怀'],
      startDelay: 0,
      typeSpeed: 200,
      loop: true,
      backSpeed: 100,
      showCursor: true
    });
  } catch (err) {
  }

</script>




<script src="/js/tocbot.min.js"></script>

<script>
  // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto',
    onClick: (e) => {
      $('.toc-link').removeClass('is-active-link');
      $(`a[href=${e.target.hash}]`).addClass('is-active-link');
      $(e.target.hash).scrollIntoView();
      return false;
    }
  });
</script>



<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/js/ayer.js"></script>



<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>


<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
  });

  MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for(i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.6/unpacked/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
  var ayerConfig = {
    mathjax: true
  }
</script>



<script src="/js/busuanzi-2.3.pure.min.js"></script>



<script type="text/javascript" src="https://js.users.51.la/20544303.js"></script>


    
  </div>
</body>

</html>